<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <div slot="header" class="clearfix">
          <span>{{title}}</span>
        </div>
        <el-form :rules="rules" ref="form" :model="form" label-width="80px">
          <!-- 学科 -->
          <el-form-item prop="subjectID" label="学科:">
            <el-select @change="subjectChange" v-model="form.subjectID" placeholder="请选择">
              <el-option
                v-for="iteam in subList"
                :key="iteam.value"
                :label="iteam.label"
                :value="iteam.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 目录 -->
          <el-form-item prop="catalogID" label="目录:">
            <el-select v-model="form.catalogID" placeholder="请选择">
              <el-option
                v-for="iteam in directorys"
                :key="iteam.value"
                :label="iteam.label"
                :value="iteam.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item prop="enterpriseID" label="企业:">
            <el-select v-model="form.enterpriseID" placeholder="请选择">
              <el-option
                v-for="iteam in companys"
                :key="iteam.id"
                :label="iteam.company"
                :value="iteam.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 城市 -->
          <el-form-item prop="city" label="城市:">
            <el-col :span="6">
              <el-select
                @change="selectProvinces"
                class="city"
                v-model="form.province"
                placeholder="请选择"
              >
                <el-option
                  v-for="(iteam,index) in citys"
                  :key="index"
                  :label="iteam"
                  :value="iteam"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select class="city" v-model="form.city" placeholder="请选择">
                <el-option v-for="(iteam,index) in area" :key="index" :label="iteam" :value="iteam"></el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <!-- 方向 -->
          <el-form-item prop="direction" label="方向:">
            <el-select v-model="form.direction" placeholder="请选择">
              <el-option
                v-for="(iteam,index) in direction"
                :key="index"
                :value="iteam"
                :label="iteam"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 题型 -->
          <el-form-item prop="questionType" label="题型:">
            <el-radio-group v-model="form.questionType">
              <el-radio
                v-for="iteam in questionType"
                :key="iteam.value"
                :label="iteam.value.toString()"
              >{{iteam.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item prop="difficulty" label="难度:">
            <el-radio-group v-model="form.difficulty">
              <el-radio
                v-for="iteam in difficulty"
                :key="iteam.value"
                :label="iteam.value.toString()"
              >{{iteam.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 题干 -->
          <el-form-item prop="question" label="题干:">
            <quill-editor class="title" v-model="form.question" :options="editorOption"></quill-editor>
          </el-form-item>
          <!-- 选项 -->
          <el-form-item label="选项:" v-if="form.questionType!=='3'">
            <div v-for="iteam in form.options" :key="iteam.id">
              <!-- 单选框 -->
              <el-radio
                @change="init(iteam)"
                v-if="form.questionType==='1'"
                v-model="iteam.isRight"
                :label="true"
              >{{iteam.code}}:</el-radio>
              <!-- 多选框 -->
              <el-checkbox
                v-if="form.questionType==='2'"
                v-model="iteam.isRight"
                :label="iteam.code"
              >{{iteam.code}}:</el-checkbox>
              <el-input v-model="iteam.title"></el-input>
              <!-- 此处使用闭包给组件固定属性传自定义参数 -->
              <!-- :before-upload="(file)=>{beforeAvatarUpload(file,iteam)}" -->
              <el-upload
                class="avatar-uploader upPic"
                action="#"
                :show-file-list="false"
                :before-upload="(file)=>{beforeAvatarUpload(file,iteam)}"
              >
                <img v-if="iteam.img" :src="iteam.img" class="avatar" />
                <i v-else class="imgPreview">上传图片</i>
                <i class="el-icon-circle-close" @click.stop="hClearImg(iteam)"></i>
              </el-upload>
            </div>
            <el-row>
              <el-col :span="5">
                <el-button
                  :disabled="form.questionType!=='2'"
                  type="danger"
                  @click="addOpt"
                >+增加选项和答案</el-button>
              </el-col>
              <el-col :span="5">
                <el-button
                  :disabled="form.questionType!=='2'"
                  type="primary"
                  @click="delOpt"
                  v-if="options > 4"
                >-减少选项和答案</el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <!-- 解析视频 -->
          <el-form-item label="解析视频:">
            <el-input v-model="form.videoURL"></el-input>
          </el-form-item>
          <!-- 答案解析 -->
          <el-form-item prop="answer" label="答案解析:" class="answer">
            <quill-editor class="title" v-model="form.answer" :options="editorOption"></quill-editor>
          </el-form-item>
          <!-- 题目备注 -->
          <el-form-item label="题目备注:">
            <el-input type="textarea" v-model="form.remarks"></el-input>
          </el-form-item>
          <!-- 试题标签 -->
          <el-form-item label="试题标签:">
            <el-select :multiple="true" v-model="form.tags" placeholder="请选择">
              <el-option
                v-for="iteam in tags"
                :key="iteam.value"
                :label="iteam.label"
                :value="iteam.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 提交按钮 -->
          <el-form-item>
            <el-button :loading="isLoading" v-if="!this.$route.query.id" type="primary" @click="hSubmit('ruleForm')">确认提交</el-button>
          </el-form-item>
          <el-form-item>
            <el-button :loading="isLoading" v-if="this.$route.query.id" type="success" @click="hSubmit('ruleForm')">确认修改</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
// 导入样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// 导入组件
import { quillEditor } from 'vue-quill-editor'
import { simple } from '@/api/hmmm/subjects'
import { difficulty, questionType, direction } from '@/api/hmmm/constants'
import { list } from '@/api/hmmm/companys'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { simple as directroys } from '@/api/hmmm/directorys.js'
import { simple as tags } from '@/api/hmmm/tags.js'
import { add, detail } from '@/api/hmmm/questions.js'
export default {
  name: 'newQuestion',
  data () {
    return {
      // 对富文本编辑器的配置
      editorOption: {
        // 占位配置
        placeholder: '',
        modules: {
          // 配置工具栏
          toolbar: [
            ['bold', 'italic', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote'],
            [{ indent: '-1' }, { indent: '+1' }],
            ['image'],
            ['code-block']
          ]
        }
      },
      // 表单域绑定数据
      form: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        answer: '',
        videoURL: '',
        remarks: '',
        tags: '',
        options: []
      },
      // 表单验证数据
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'blur' }
        ],
        city: [{ required: true, message: '请选择城市', trigger: 'blur' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'blur' }
        ],
        question: [
          { required: true, message: '请输入题干名称', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' }
        ]
      },
      // 表单初始化数据
      difficulty,
      questionType,
      direction,
      subList: [],
      companys: [],
      citys: provinces(),
      area: [],
      directorys: [],
      tags: [],
      // 选项个数
      options: 4,
      // 提交和修改按钮状态
      isLoading: false
    }
  },
  created () {
    this.addOption(this.options)
    this.getSubject()
    this.getCompany()
    this.isChange()
  },
  methods: {
    // 判断是否为修改
    isChange () {
      if (this.$route.query.id) {
        console.log('修改')
        this.getEditData()
      } else {
        console.log('新增')
      }
    },
    // 若为修改，请求数据
    async getEditData () {
      try {
        const data = {}
        data.id = this.$route.query.id
        const res = await detail(data)
        console.log(res.data)
        // 此处需字符串转数组
        res.data.tags = res.data.tags.split(',')
        console.log(res.data.tags)
        // tags里的每一项需转为数字
        // res.data.tags.forEach((elem, index) => {
        //   this.$set(res.data.tags, index, parseInt(elem))
        // })
        // 选项是否选中返回数字需转换为布尔值
        res.data.options.forEach((elem) => {
          elem.isRight = !!elem.isRight
        })
        // res.data.isRight = !!res.data.isRight
        console.log(res.data.tags)
        this.form = res.data
        // 触发学科联动
        this.subjectChange()
      } catch (err) {
        console.log(err)
        this.$message.error('无法获取试题信息')
      }
    },
    // 获取学科列表
    async getSubject () {
      const subList = await simple()
      console.log(subList.data)
      this.subList = subList.data
    },
    // 获取企业列表
    async getCompany () {
      const companys = await list()
      console.log(companys.data.items)
      this.companys = companys.data.items
    },
    // 获取省份
    getProvinces () {
      provinces()
    },
    // 城市下拉事件
    selectProvinces () {
      console.log(this.form.province)
      // 更换城市后，置空地区选项
      this.form.city = ''
      this.area = citys(this.form.province)
    },
    // 学科列表改变触发
    subjectChange () {
      this.getDirectroys()
      this.getTags()
    },
    // 获取目录
    async getDirectroys () {
      if (!this.$route.query.id) {
        this.form.catalogID = ''
      }
      const dst = await directroys({ subjectID: this.form.subjectID })
      console.log(dst)
      this.directorys = dst.data
    },
    // 获取标签
    async getTags () {
      if (!this.$route.query.id) {
        this.form.tags = ''
      }
      const dst = await tags({ subjectID: this.form.subjectID })
      console.log(dst)
      this.tags = dst.data
    },
    // 试题图片上传前的文件校验
    beforeAvatarUpload (file, iteam) {
      // console.log(iteam)
      // console.log(file)
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      if (isJPG && isLt2M) {
        iteam.img = URL.createObjectURL(file)
      }
      return isJPG && isLt2M
    },
    // 关闭按钮清除图片
    hClearImg (iteam) {
      iteam.img = ''
    },
    // 添加选项数据
    addOption (num) {
      for (let i = 0; i < num; i++) {
        // this.form.options[i] = {
        //   id: i,
        //   code: String.fromCharCode(65 + i),
        //   title: '',
        //   img: '',
        //   isRight: false
        // }
        this.$set(this.form.options, i, {
          id: i,
          code: String.fromCharCode(65 + i),
          title: '',
          img: '',
          isRight: false
        })
      }
    },
    // 添加选项
    addOpt () {
      if (this.options < 7) {
        this.options = this.options + 1
        // this.addOption(this.options)
        this.form.options.push({
          id: this.options - 1,
          code: String.fromCharCode(65 + this.options - 1),
          title: '',
          img: '',
          isRight: false
        })
      } else {
        this.$message.error('够多了，不能再添加了哦')
      }
    },
    // 删除选项
    delOpt () {
      if (this.options > 4) {
        this.options = this.options - 1
        this.form.options.pop()
      } else {
        this.$message.error('不能再删了')
      }
    },
    // 初始化单选按钮
    init (data) {
      console.log(data)
      console.log(this.form.options)
      this.form.options.forEach((iteam) => {
        iteam.isRight = false
      })
      data.isRight = true
      console.log(data)
    },
    // 确认提交按钮
    hSubmit (formName) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          // 登录按钮加载状态
          this.isLoading = true
          // 标签数据处理
          this.form.tags = this.form.tags.join(',')
          try {
            const res = await add(this.form)
            console.log(res)
            this.$message.success('提交成功')
            this.$router.push({
              path: '/questions/list'
            })
            // 登录按钮退出加载状态
            this.isLoading = true
          } catch (error) {
            console.log(error)
            this.$message.error('出错了！！！')
          }
        } else {
          console.log('error submit!!')
          this.$message.error('请按要求填写表单')
          return false
        }
      })
    }
  },
  // 注册组件
  components: {
    quillEditor
  },
  // 标题计算属性
  computed: {
    title: function () {
      if (this.$route.query.id) {
        return '修改试题'
      } else {
        return '录入试题'
      }
    }
  },
  watch: {
    'form.questionType': function (a, b) {
      console.log(a, b)
      if (a === '1') {
        this.options = 4
        // 保留选项中的内容
        this.form.options = this.form.options.slice(0, 4)
        // 多选变单选，不用全部选中
        this.form.options.forEach((iteam) => {
          iteam.isRight = false
        })
      }
    }
  }
}
</script>

<style scoped>
.upPic {
  display: inline-block;
  margin-left: 10px;
  vertical-align: -webkit-baseline-middle;
}
.title /deep/ .ql-container {
  height: 300px;
}
.el-select,
.el-input,
.el-textarea {
  width: 450px;
}
.city {
  width: 200px;
}
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  height: 60px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar {
  object-fit: cover;
  width: 120px;
  height: 60px;
}
.imgPreview {
  display: inline-block;
  font-size: 14px;
  font-style: normal;
  line-height: 50px !important;
  color: #8c939d;
  width: 120px;
  height: 60px;
  line-height: 60px;
  text-align: center;
}
.el-icon-circle-close {
  position: absolute;
  top: 0;
  right: 0;
}
/* 防止文本域拖拽 */
.el-textarea /deep/ .el-textarea__inner {
  resize: none;
}
.answer /deep/ .el-form-item__label {
  margin-left: -20px;
  width: 100px !important;
}
</style>
